from flask import Flask, request
import socket

app = Flask(__name__)

@app.route('/')
def log_visitor_info():
    visitor_ip = request.remote_addr
    user_agent = request.headers.get('User-Agent')
    referer = request.headers.get('Referer')
    cookies = request.cookies
    request_time = request.date
    request_path = request.path

    log_entry = (
        f"IP: {visitor_ip}, "
        f"User-Agent: {user_agent}, "
        f"Referer: {referer}, "
        f"Cookies: {cookies}, "
        f"Time: {request_time}, "
        f"Path: {request_path}"
    )

    # 打印到终端
    print(log_entry)
    
    # 记录到文件
    with open('log/visitor_log.txt', 'a') as log_file:
        log_file.write(log_entry + '\n')
    
    return 'Visitor info logged.'

def is_port_in_use(port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex(('0.0.0.0', port)) == 0

def start_server(host, port):
    while True:
        if is_port_in_use(port):
            print(f"Port {port} is already in use. Please enter a new port:")
            port = int(input("New port: "))
        else:
            try:
                app.run(host=host, port=port)
                break
            except OSError as e:
                print(f"Failed to start server on port {port}: {e}")
                port = int(input("Enter a new port: "))

if __name__ == '__main__':
    host = '0.0.0.0'
    port = 8080
    start_server(host, port)
# pip install flask
# sansjtw